<?php

namespace App\Models;

use App\Services\GoodsService;
use App\Services\OrderService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class ShopTrans extends Model
{
    use HasFactory;
    protected $table = 'sp_shop_trans';
    protected $primaryKey = 'id';
    public $timestamps = false;

    const ORDER_STATUS_FINISH = 1;//已到账

    const ORDER_TRANS_TYPE_SETTLE = 1;//结算
    const ORDER_TRANS_TYPE_REFUND = 2;//退款
    const ORDER_TRANS_TYPE_CHARGE = 3;//充值
    const ORDER_TRANS_TYPE_BUYOUT = 4;//买断
    const ORDER_TRANS_TYPE_WITHDRAWAL = 6;//提现
    const ORDER_TRANS_TYPE_SERVICE_CHARGE = 7;//增值服务业务充值
    const ORDER_TRANS_TYPE_PROCURE_CHARGE = 8;//采购账户充值

    const ORDER_TRANS_TYPE_LIST = [
        "1"=>'结算',
        "2"=>'退款',
        "3"=>'充值',
        "4"=>'买断',
        "6"=>'提现',
        "7"=>'增值服务业务充值',
        "8"=>'采购账户充值',
    ];

    //获取退款
    protected function getOrderRefundTrans($order,$order_lease){
        $order_rate = OrderRate::getOrderRate($order['order_id'],$order['is_skip']);
        if(empty($order_rate)){
            return false;
        }
        $fee_rate = 0;
        $fixed_fee = 0;
        $service_fee = 0;
        $settle_amount = 0;
        $trans_detail = [];
        if($order['financing_type'] == ShopUser::SHOP_USER_ACCOUNT_RONG){//融资

        }elseif($order['financing_type'] == ShopUser::SHOP_USER_ACCOUNT_NOT_RONG){//非融资
            if($order_lease['status'] == OrderLease::ORDER_LEASE_STATUS_PAID) {//已支付
                if ($order_lease['settle_type'] == OrderLease::ORDER_LEASE_SETTLE_STATUS_YES) {//已结算
                    $settle_amount = $order_lease['paid_rent'];
                } else {//未结算
                    if ($order_lease['which_period'] == 1) {//首期
                        $fixed_fee = $order_rate['fixed_fee'];
                        $trans_detail['risk_amount'] = $order_rate['risk_amount'];
                        $trans_detail['contract_amount'] = $order_rate['smartcontract_amount'];
                        $trans_detail['realname_amount'] = $order_rate['realname_amount'];
                    } else {
                        $fixed_fee                     = 0;
                        $trans_detail['risk_amount']     = 0;
                        $trans_detail['contract_amount'] = 0;
                        $trans_detail['realname_amount'] = 0;
                    }
                    $fee_rate = 0;
                    $service_fee  = $fixed_fee;
                    $settle_amount = $fixed_fee;
                }
            }else{
                if($order_lease['which_period'] == 1){//首期
                    $fixed_fee = $order_rate['fixed_fee'];
                    $settle_amount = $fixed_fee;
                    $trans_detail['risk_amount'] = $order_rate['risk_amount'];
                    $trans_detail['contract_amount'] = $order_rate['smartcontract_amount'];
                    $trans_detail['realname_amount'] = $order_rate['realname_amount'];
                }
            }
        }
        $data['settle_amount'] = $settle_amount;
        $data['service_fee'] = $service_fee;
        $data['fee_rate'] = $fee_rate;
        $data['fixed_fee'] = $fixed_fee;
        $data['trans_detail'] = $trans_detail;
        return $data;
    }

    //添加退款流水记录
    protected function addOrderTrans($order,$settle_amount,$service_fee,$alipay_trade_no,$remarks,$order_lease_id,$fee_rate,$fixed_fee,$trans_detail,$trans_type){
        $shop_balance = ShopUser::where('member_id',$order['seller_id'])->value('shop_balance');
        $shop_balance = $shop_balance?$shop_balance:0;
        // dd($trans_type);
        if($this->where([['order_id',$order['order_id']],['member_id',$order['seller_id']],['order_lease_id',$order_lease_id],['trans_type',$trans_type]])->count() == 0){


            DB::beginTransaction();
            $data['order_id'] = $order['order_id'];
            $data['member_id'] = $order['seller_id'];
            $data['user_id'] = $order['uid'];
            $data['order_lease_id'] = $order_lease_id;
            if($trans_type == self::ORDER_TRANS_TYPE_REFUND){
                $data['amount'] = -$settle_amount;
            }else{
                $data['amount'] = $settle_amount;
            }
            $data['before_balance'] = $shop_balance;
            $data['after_balance'] = $shop_balance+$data['amount'];
            $data['service_fee'] = sprintf("%01.4f",$service_fee);
            $data['order_rate'] = sprintf("%01.4f",$fee_rate);
            $data['order_fixed_cost'] = $fixed_fee;
            $data['trade_no'] = !empty($alipay_trade_no)?$alipay_trade_no:0;
            $data['trans_type'] = $trans_type;
            $data['status'] = 1;
            $data['remarks'] = $remarks;
            $data['create_time'] = date('Y-m-d H:i:s');
            if($data['after_balance']<0){
                return false;
            }
            $trans_id = $this->insertGetId($data);
            $res = ShopUser::where('member_id',$order['seller_id'])->update(['shop_balance'=>$data['after_balance']]);

            if($res && $trans_id){
                if($trans_detail && $res){
                    $trans_detail['trans_id'] = $trans_id;
                    $trans_detail['order_id'] = $order['order_id'];
                    $trans_detail['order_lease_id'] = $order_lease_id;
                    $tres = TransDetail::insert($trans_detail);
                    if($tres){
                        DB::commit();
                        return true;
                    }else {
                        DB::rollBack();
                        return false;
                    }
                }else{
                    DB::commit();
                    return true;
                }
            }else{
                DB::rollBack();
                return false;
            }
        }else{
            DB::rollBack();
            return false;
        }
    }

    //花呗退款
    protected function getHuabeiOrderRefundTrans($order){
        $order_rate = OrderRate::getOrderRate($order['order_id'],$order['is_skip']);
        if($order['settlement_status'] == OrderService::HUABEI_ORDER_SETTLE_STATUS_YES){//已结算
            $fixed_fee = 0;
            $fee_rate = 0;
            $settle_amount = $order['rent_total'];
            $service_fee = 0;
            $trans_detail = [];
        }else{//未结算
            $fixed_fee = $order_rate['fixed_fee'];
            $trans_detail['risk_amount'] = $order_rate['risk_amount'];
            $trans_detail['contract_amount'] = $order_rate['smartcontract_amount'];
            $trans_detail['realname_amount'] = $order_rate['realname_amount'];
            $huabei_fee = 0;
            //商户承担手续费  15天以上 退款扣除花呗手续费
            if($order['huabei_fee_bear'] == GoodsService::GOODS_HUABEI_FEE_MERCHANT && $order['pay_time'] + 15*24*3600 < time()){
                $shop_fee_ratio = GoodsHuabei::HUABEI_SHOP_FEE_BEAR_LIST;
                $huabei_fee = round($order['rent_total'] * $shop_fee_ratio[$order['huabei_stages']] * 0.01,2);
                $fee_rate = $order_rate['huabei_rate'];
            }else{
                $fee_rate = 0;
            }
            $service_fee = sprintf("%01.4f",$fixed_fee + $huabei_fee + $order['rent_total'] * $fee_rate * 0.01);
            $settle_amount = $service_fee;
            $trans_detail['huabei_fee'] = $huabei_fee;
            $trans_detail['withhold_rate'] = 0;
            $trans_detail['file_rate'] = 0;
            $trans_detail['platform_rate'] = 0;
            $trans_detail['insurance_rate'] = 0;
            $trans_detail['financing_rate'] = 0;
            $trans_detail['platform_amount'] = 0;
            $trans_detail['insurance_amount'] = 0;
            $trans_detail['financing_amount'] = 0;
            $trans_detail['file_amount'] = 0;
            $trans_detail['withhold_amount'] = 0;
        }
        $data['settle_amount'] = $settle_amount;
        $data['service_fee'] = $service_fee;
        $data['fee_rate'] = $fee_rate;
        $data['fixed_fee'] = $fixed_fee;
        $data['trans_detail'] = $trans_detail;
        return $data;
    }

    //花呗退款添加数据
    protected function addHuabeiTrans($order,$settle_amount,$service_fee,$alipay_trade_no,$remarks,$fee_rate,$fixed_fee,$trans_detail){
        $shop_balance = ShopUser::where('member_id',$order['seller_id'])->value('shop_balance');
        $shop_balance = $shop_balance?$shop_balance:0;
        DB::beginTransaction();
        $data['order_id'] = $order['order_id'];
        $data['member_id'] = $order['seller_id'];
        $data['user_id'] = $order['uid'];
        $data['amount'] = -$settle_amount;
        $data['before_balance'] = $shop_balance;
        $data['after_balance'] = $shop_balance-$settle_amount;
        $data['service_fee'] = sprintf("%01.4f",$service_fee);
        $data['order_rate'] = sprintf("%01.4f",$fee_rate);
        $data['order_fixed_cost'] = $fixed_fee;
        $data['trade_no'] = !empty($alipay_trade_no)?$alipay_trade_no:0;
        $data['trans_type'] = 2;
        $data['status'] = 1;
        $data['remarks'] = $remarks;
        $data['create_time'] = date('Y-m-d H:i:s');
        $trans_id = $this->insertGetId($data);
        $res = ShopUser::where('member_id',$order['seller_id'])->update(['shop_balance'=>$data['after_balance']]);
        $lease_res = OrderLease::where([['order_id',$order['order_id']],['type',1]])->update(['status'=>OrderLease::ORDER_LEASE_STATUS_REFUNDED]);
        $order_data['status']      = OrderService::ORDER_STATUS_REFUND_SUCCESS;
        $order_data['update_time'] = time();
        $reg = Order::where('id',$order['order_id'])->update($order_data);
        if($res && $trans_id && $lease_res && $reg){
            if($trans_detail && $trans_id){
                $trans_detail['trans_id'] = $trans_id;
                $trans_detail['order_id'] = $order['order_id'];
                $tres = TransDetail::insert($trans_detail);
                if($tres){
                    DB::commit();
                    return true;
                }else {
                    DB::rollBack();
                    return false;
                }
            }else{
                DB::commit();
                return true;
            }
        }else{
            DB::rollBack();
            return false;
        }
    }

    //添加
    protected function addData($data)
    {
        return $data = $this->insert($data);
    }

    //通过订单获取结算信息
    protected function getShopTransByOrder($order_id,$order_lease_id){
        $trans = $this->where([['order_id',$order_id],['order_lease_id',$order_lease_id],['status',self::ORDER_STATUS_FINISH],['trans_type',self::ORDER_TRANS_TYPE_SETTLE]])->select('order_rate','order_fixed_cost','service_fee','amount')->first();
        $trans = $trans ? $trans->toArray() : [];
        return $trans;
    }

    //获取花呗订单结算信息
    protected function getHuabeiOrderShopTrans($order_id){
        $trans = $this->where([['order_id',$order_id],['status',self::ORDER_STATUS_FINISH],['trans_type',self::ORDER_TRANS_TYPE_SETTLE]])->select('order_rate','order_fixed_cost','service_fee','amount','create_time')->first();
        $trans = $trans ? $trans->toArray() : [];
        return $trans;
    }

    //获取结算详情
    protected function getSettleData($order){
        $category_id = Goods::where('id',$order['goods_id'])->value('category_id');
        $source_id = Source::where('source_code',trim($order['order_from']=='qrcode'?'qrcode':($order['order_from']=='saleOffline'?'saleOffline':'search')))->value('id');
        $goods_rate=[];
        if(!empty($source_id)) {//!empty($category_id) &&
            $goods_rate = GoodsRate::where([['member_id', $order['seller_id']],  ['source_id', $source_id], ['is_delete', GoodsRate::GOODS_RATE_NOT_DELETE]])
                ->select('goods_rate', 'smartcontract as smartcontract_amount', 'realname as realname_amount', 'risk as risk_amount',
                    'platform as platform_rate', 'withhold as withhold_rate','is_preposition', 'file as file_rate', 'financing as financing_rate','post_deduction')->first();
            $goods_rate = $goods_rate ? $goods_rate->toArray() : [];
        }
        if(empty($goods_rate)){
            return false;
        }
        $order=array_merge($order,$goods_rate);
        $trans_detail = [];
        $fixed_fee = 0;
        $fee_rate = 0;
        if($order['financing_type'] == Order::FINANCING_TYPE_RONG){//融资
            if($order['which_period'] == 1){//首期
                if($order['is_skip'] == Order::RISK_SKIP_YES){//跳过风控
                    $fixed_fee = $order['smartcontract_amount'] + $order['realname_amount'] ;
                    $trans_detail['risk_amount'] = 0;
                }else{
                    $fixed_fee = $order['smartcontract_amount'] + $order['realname_amount'] + $order['risk_amount'];
                    $trans_detail['risk_amount'] = $order['risk_amount'];
                }
                $trans_detail['contract_amount'] = $order['smartcontract_amount'];
                $trans_detail['realname_amount'] = $order['realname_amount'];
                $trans_detail['withhold_rate'] = $order['withhold_rate'];
            }else{
                $fixed_fee = 0;
                $trans_detail['risk_amount'] = 0;
                $trans_detail['contract_amount'] = 0;
                $trans_detail['realname_amount'] = 0;
            }
            $fee_rate = $order['withhold_rate'] + $order['file_rate'] + $order['financing_rate'] + $order['insure_rate'] + $order['platform_rate'];
            $trans_detail['file_rate'] = $order['file_rate'];
            $trans_detail['platform_rate'] = $order['platform_rate'];
            $trans_detail['insurance_rate'] = $order['insure_rate'];
            $trans_detail['financing_rate'] = $order['financing_rate'];
            $trans_detail['withhold_rate'] = $order['withhold_rate'];
        }elseif($order['financing_type'] == Order::FINANCING_TYPE_NORONG) {//非融资
            if($order['which_period'] == 1){//首期
                if($order['is_skip'] == Order::RISK_SKIP_YES){//跳过风控
                    $fixed_fee = $order['smartcontract_amount'] + $order['realname_amount'];
                    $trans_detail['risk_amount'] = 0;
                }else{
                    $fixed_fee = $order['smartcontract_amount'] + $order['realname_amount'] + $order['risk_amount'];
                    $trans_detail['risk_amount'] = $order['risk_amount'];
                }
                $trans_detail['contract_amount'] = $order['smartcontract_amount'];
                $trans_detail['realname_amount'] = $order['realname_amount'];
                $trans_detail['withhold_rate'] = $order['withhold_rate'];
            }else{
                $fixed_fee = 0;
                $trans_detail['risk_amount'] = 0;
                $trans_detail['contract_amount'] = 0;
                $trans_detail['realname_amount'] = 0;
                $trans_detail['withhold_rate'] = 0;
            }
            $fee_rate = $order['withhold_rate'] + $order['file_rate'] + $order['platform_rate'];
            $trans_detail['file_rate'] = $order['file_rate'];
            $trans_detail['platform_rate'] = $order['platform_rate'];
            $trans_detail['insurance_rate'] = 0;
            $trans_detail['financing_rate'] = 0;
            $trans_detail['withhold_rate'] = $order['withhold_rate'];
        }
        $trans_detail['insure_rate']='0.00';
        $data['trans_detail'] = $trans_detail;
        $data['fixed_fee'] = $fixed_fee;
        $data['fee_rate'] = $fee_rate;
        $data['is_preposition'] = $goods_rate['is_preposition'];
        $data['post_deduction'] = $goods_rate['post_deduction'];
            return $data;
    }

    //获取结算详情
    protected function getHuabeiSettleData($order){
        $trans_detail = [];
        $fixed_fee = 0;
        $fee_rate = 0;
        if($order['financing_type'] == Order::FINANCING_TYPE_RONG){//融资
            if($order['is_skip'] == Order::RISK_SKIP_YES){//跳过风控
                $fixed_fee = $order['smartcontract_amount'] + $order['realname_amount'];
                $trans_detail['risk_amount'] = 0;
            }else{
                $fixed_fee = $order['smartcontract_amount'] + $order['realname_amount'] + $order['risk_amount'];
                $trans_detail['risk_amount'] = $order['risk_amount'];
            }
            $fee_rate = $order['withhold_rate'] + $order['file_rate'] + $order['financing_rate'] + $order['platform_rate'] + $order['huabei_rate'];
            $trans_detail['contract_amount'] = $order['smartcontract_amount'];
            $trans_detail['realname_amount'] = $order['realname_amount'];
            $trans_detail['withhold_rate'] = $order['withhold_rate'];
            $trans_detail['file_rate'] = $order['file_rate'];
            $trans_detail['platform_rate'] = $order['platform_rate'];
            $trans_detail['insurance_rate'] = $order['insure_rate'];
            $trans_detail['financing_rate'] = $order['financing_rate'];
        }elseif($order['financing_type'] == Order::FINANCING_TYPE_NORONG) {//非融资
            if($order['is_skip'] == Order::RISK_SKIP_YES){//跳过风控
                $fixed_fee = $order['smartcontract_amount'] + $order['realname_amount'];
                $trans_detail['risk_amount'] = 0;
            }else{
                $fixed_fee = $order['smartcontract_amount'] + $order['realname_amount'] + $order['risk_amount'];
                $trans_detail['risk_amount'] = $order['risk_amount'];
            }
            $trans_detail['contract_amount'] = $order['smartcontract_amount'];
            $trans_detail['realname_amount'] = $order['realname_amount'];
            $trans_detail['withhold_rate'] = $order['withhold_rate'];
            $fee_rate = $order['withhold_rate'] + $order['file_rate'] + $order['platform_rate']+ $order['huabei_rate'];
            $trans_detail['file_rate'] = $order['file_rate'];
            $trans_detail['platform_rate'] = $order['platform_rate'];
            $trans_detail['withhold_rate'] = $order['withhold_rate'];
            $trans_detail['insurance_rate'] = 0;
            $trans_detail['financing_rate'] = 0;
        }
        $data['trans_detail'] = $trans_detail;
        $data['fixed_fee'] = $fixed_fee;
        $data['fee_rate'] = $fee_rate;
        return $data;
    }






}
